package com.ehualu.check.utils;

import com.ehualu.check.es.EsUpdateUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @Author: 吴敬超
 * @Date: 2021/3/18 11:42
 */
public class CheckUtil {
    private static final Logger LOG = LoggerFactory.getLogger(CheckUtil.class);


    /**
     * 根据配置生成校验码
     *
     * @param id
     * @param extPath
     * @param extHashMothod
     * @throws IOException
     */
    public void checkfile(String id, String extPath, String extHashMothod) throws IOException {

        LOG.info("哈希校验方法 0-MD5 1-SHA256：" + extHashMothod);

        String hex;

        //md5校验
        if (extHashMothod.equals("0")) {

            hex = DigestUtils.md5Hex(new FileInputStream(new File(extPath)));

            //SHA256
        } else {

            hex = DigestUtils.sha256Hex(new FileInputStream(new File(extPath)));

        }

        LOG.info("文件校验码为：" + hex);

        MysqlUtil mysqlUtil = new MysqlUtil();
        mysqlUtil.updateCheckinfo(id, hex, "1");


    }


    /**
     * 两种校验码都生成
     *
     * @param id
     * @param extPath
     * @throws IOException
     */
    public void checkfile(String id, String extPath) throws IOException {


        String md5hex = DigestUtils.md5Hex(new FileInputStream(new File(extPath)));

        String sha256hex = DigestUtils.sha256Hex(new FileInputStream(new File(extPath)));

        LOG.info("文件md5校验码为：" + md5hex);
        LOG.info("文件sha256校验码为：" + sha256hex);

        MysqlUtil mysqlUtil = new MysqlUtil();
        mysqlUtil.updateCheckinfo(id, md5hex, sha256hex, "1");

        EsUpdateUtil esUpdateUtil = new EsUpdateUtil();
        try {
            esUpdateUtil.updateIndex(id,
                    "md5Hash", md5hex,
                    "sha256Hash", sha256hex,
                    "extHashStatus", "1");
        } catch (Exception e) {
            LOG.info("修改失败id："+id);
            e.printStackTrace();
        }


    }

/*
    public static void main(String[] args) {


        try {


            CheckUtil checkUtil = new CheckUtil();
            checkUtil.checkfile("12122", "D:\\HDP2.6.5搭建手册\\scala-2.11.12.tgz", "0");
            checkUtil.checkfile("12122", "D:\\HDP2.6.5搭建手册\\scala-2.11.12.tgz", "1");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
*/


}
